import re

from django.contrib.auth.hashers import make_password,check_password
from django.core.mail import send_mail
from django.db.models import F
from django.shortcuts import render
from rest_framework.views import APIView
from .models import Story,User,UserInfo,Author,Cate,Section,Grade
from rest_framework.response import Response
from .serializers import *
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
from django.conf import settings
serializer = Serializer(settings.SECRET_KEY, 600)

class GradeApi(APIView):

    def get(self,request):
        grade_data = Grade.objects.all()
        grade_serializer = GradeSerializers(grade_data,many=True)
        return Response(grade_serializer.data)

    def post(self,request):
        grade_data = request.data
        if Grade.objects.filter(grade=grade_data.get("grade")):
            return Response({"msg":"已经有该等级","code":400})
        else:
            grade_serializer = GradeSerializers(data=grade_data)
            if grade_serializer.is_valid():
                grade_serializer.save()
                return Response({"msg":"ok","code":200})
            else:
                print(grade_serializer.errors)
                return Response({"msg":"添加失败","code":400})

    def delete(self,request):
        gid = request.data.get("gid")
        grade_obj = Grade.objects.filter(pk=gid)
        if grade_obj:
            grade_obj.delete()
            return Response({"msg":"ok","code":200})
        else:
            return Response({"msg":"没有搞等级","code":400})

    def put(self,request):
        gid = request.data.get("gid")
        grade = request.data.get("grade")
        print(grade)
        grade_obj = Grade.objects.filter(pk=gid)
        grade_obj.update(grade=grade)
        return Response({"msg":"ok","code":200})


class UserApi(APIView):

    def get(self,request):
        user_data = User.objects.all()
        user_serializers = UserSerializers(user_data,many=True)
        return Response(user_serializers.data)

    def post(self,request):
        user_data = request.data
        if User.objects.filter(username=user_data.get("username")):
            return Response({"msg": "已经有该用户", "code": 400})
        if not re.match(r'[0-9a-zA-z_]{0,19}@(.*?).com', user_data.get("email")):
            return Response({"msg": "邮箱不合法", "code": 400})
        if user_data.get("password") == user_data.get("password2"):
            user_dict = {
                'username':user_data.get("username"),
                'password':make_password(user_data.get("password")),
                'email':user_data.get("email")
            }
            user_serializers = UserSerializers(data=user_dict)

            if user_serializers.is_valid():
                user_serializers.save()
                print(user_serializers.data.get("id"))
                subject = "欢迎注册"
                message = "欢迎注册"
                from_email = settings.EMAIL_FROM
                recipient_list = [user_data.get("email")]
                html_message = '<h2>请点击下面链接进行激活<a href="http://127.0.0.1:8000/app01/activateuser/?token={}">激活请点击这里</a></h2>'.format(user_serializers.data.get("id"))
                send_mail(subject=subject,
                          message=message,
                          from_email=from_email,
                          recipient_list=recipient_list,
                          html_message=html_message)
                return Response({"msg":"ok","code":200})
            else:
                print(user_serializers.errors)
                return Response({"msg": "注册失败", "code": 400})
        else:
            return Response({"msg": "两次密码不一致", "code": 400})

class ActivateUser(APIView):
    def get(self,request):
        try:
            token = request.GET.get("token")
            # # user_info = serializer.loads(token)
            user_obj = User.objects.filter(pk=token)
            user_obj.update(state=1)
            return Response({"msg":"ok", "code": 200})
        except SignatureExpired:
            return Response({"msg":"激活失败","code":400})


class LoginUser(APIView):

    def post(self,request):
        user_data = request.data
        user_obj = User.objects.filter(username=user_data.get("username"))
        if user_obj:
            if check_password(user_obj.password,user_data.get("password")):
                return Response({'msg':"ok","code":200,"user_id":user_obj.id})
            else:
                return Response({"msg": "用户名或密码错误", "code": 400})
        else:
            return Response({"msg":"用户名或密码错误","code":400})


class CateApi(APIView):

    def post(self,request):
        cate_data = request.data
        if Cate.objects.filter(cate=cate_data.get("cate")):
            return Response({"msg":"已经有该分类","code":400})
        else:
            cate_serializer = CateSerializers(data=cate_data)
            if cate_serializer.is_valid():
                cate_serializer.save()
                return Response({"msg":"ok","code":200})
            else:
                print(cate_serializer.errors)
                return Response({"msg":"添加分类","code":400})

    def get(self,request):
        cate_data = Cate.objects.all()
        cate_serializer = CateSerializers(cate_data,many=True)
        return Response(cate_serializer.data)

    def put(self,request):
        cid = request.data.get("cid")
        cate = request.data.get("cate")
        cate_obj = Cate.objects.filter(pk=cid)
        cate_obj.update(cate=cate)
        return Response({"msg":"ok","code":200})

    def delete(self,request):
        cid = request.data.get("cid")
        cate_obj = Cate.objects.filter(pk=cid)
        cate_obj.delete()
        return Response({'msg':"ok","code":200})


class StoryApi(APIView):

    def post(self,request):
        story_data = request.data
        if Story.objects.filter(name=story_data.get("name")):
            return Response({"msg":"已经有该小说","code":400})
        else:
            story_serializer = CateSerializers(data=story_data)
            if story_serializer.is_valid():
                story_serializer.save()
                return Response({"msg":"ok","code":200})
            else:
                print(story_serializer.errors)
                return Response({"msg":"添加分类","code":400})

    def get(self, request, cid):
        cate_obj = Cate.objects.filter(pk=cid).first()
        story_obj = Story.objects.filter(cate=cate_obj)
        story_serializer = CateSerializers(story_obj,many=True)
        return Response(story_serializer.data)

    def put(self,request):
        sid = request.data.get("sid")
        name = request.data.get("name")
        author = request.data.get("author")
        price = request.data.get("price")
        img = request.data.get("img")
        introduce = request.data.get("introduce")
        cate = request.data.get("cate")
        story_obj = Story.objects.filter(pk=sid)
        story_obj.update(
            name= name,
            author=Author.objects.first(pk=author).first(),
            price=price,
            img=img,
            introduce=introduce,
            cate=Cate.objects.filter(pk=cate).first(),
        )
        return Response({"msg":"ok","code":200})

    def delete(self,request):
        sid = request.data.get("sid")
        story_obj = Story.objects.filter(pk=sid)
        story_obj.delete()
        return Response({'msg':"ok","code":200})


class SectionApi(APIView):

    def post(self,request):
        section_data = request.data
        if Section.objects.filter(name=section_data.get("name")):
            return Response({"msg":"已经有该章节","code":400})
        else:
            section_serializer = SectionSerializers(data=section_data)
            if section_serializer.is_valid():
                section_serializer.save()
                return Response({"msg":"ok","code":200})
            else:
                print(section_serializer.errors)
                return Response({"msg":"添加失败","code":400})

    def get(self,request, sid):
        story_obj = Story.objects.filter(pk=sid).first()
        story_obj.update(reading=F('reading')+1)
        section_data = Section.objects.filter(story=story_obj)
        section_serializer = SectionSerializers(section_data,many=True)
        return Response(section_serializer.data)

    def put(self,request):
        sid = request.data.get("sid")
        section_obj = Section.objects.filter(pk=sid)
        name = request.data.get("name")
        story = Story.objects.filter(pk=request.data.get("story")).first()
        content = request.data.get("content")
        section_obj.update(
            name=name,
            story=story,
            content=content
        )
        return Response({"msg":"ok","code":200})

    def delete(self,request):
        sid = request.data.get("sid")
        story_obj = Story.objects.filter(pk=sid)
        story_obj.delete()
        return Response({"msg":"ok","code":200})